<template>
    <div class="vue-body">
        <!-- 搜索条件, 按钮 放在一行 -->
        <div class="btn-header">
            <!-- 搜索条件 -->
            <div>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入角色名称" suffix-icon="el-icon-search"
                          v-model="params.name"></el-input>
                <el-input style="width: 200px; margin-right: 5px;" placeholder="请输入角色标识" suffix-icon="el-icon-position"
                          v-model="params.code"></el-input>
                <el-button type="primary" @click="load">搜索</el-button>
            </div>
            
            <!-- 操作按钮 -->
            <div class="btn-inner-div">
                <el-button type="primary" @click="add">新增 <i class="el-icon-circle-plus-outline"></i></el-button>
                <el-button type="danger">批量删除 <i class="el-icon-remove-outline"></i></el-button>
                <el-button type="primary">导入 <i class="el-icon-bottom"></i></el-button>
                <el-button type="primary">导出 <i class="el-icon-top"></i></el-button>
            </div>
        </div>
        
        <!-- 列表查询 -->
        <el-table :data="tableData" border stripe :header-cell-class-name="headerBg" v-loading="loading">
            <el-table-column prop="id" label="角色ID" width="100" sortable align="center"></el-table-column>
            <el-table-column prop="name" label="角色名称" width="200" align="center"></el-table-column>
            <el-table-column prop="code" label="角色标识" width="200" align="center"></el-table-column>
            <el-table-column prop="remark" label="角色描述" width="300" align="center"></el-table-column>
            <el-table-column prop="deleted" label="启用状态" width="200" align="center">
                <template slot-scope="scope"> <!-- 1打开， 0关闭 -->
                    <el-switch v-model="scope.row.deleted" :active-value="0" :inactive-value="1"></el-switch>
                </template>
            </el-table-column>
            <el-table-column prop="createtime" label="创建时间" width="200" sortable align="center"
                             :formatter="formatDate"></el-table-column>
            <el-table-column prop="updatetime" label="更新时间" width="200" sortable align="center"
                             :formatter="formatDate"></el-table-column>
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button type="success" size="mini" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit"></i>
                    </el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除 <i
                         class="el-icon-remove-outline"></i></el-button>
                </template>
            </el-table-column>
        </el-table>
        
        <!-- 分页查询 -->
        <div style="padding: 10px 0; text-align: left;">
            <el-pagination
                 @size-change="handleSizeChange"
                 @current-change="handleCurrentChange"
                 :current-page="pageNum"
                 :page-sizes="[5, 10, 20, 50]"
                 :page-size="pageSize"
                 layout="total, sizes, prev, pager, next, -> , jumper"
                 :total="total">
            </el-pagination>
        </div>
        
        <!-- 数据新增界面 -->
        <el-dialog top="25vh" title="用户新增"
                   :visible.sync="dialogFormVisible"
                   append-to-body
                   :close-on-click-modal=true
                   width="30%"
        >
            <el-form ref="form" :model="form" label-width="120px" :rules="roles">
                <el-form-item label="角色名称" prop="name">
                    <el-input prefix-icon="el-icon-user-solid" v-model="form.name" style="width: 90%"
                              placeholder="请输入角色名称"></el-input>
                </el-form-item>
                <el-form-item label="角色菜单">
                    <el-tree
                         class="tree-border"
                         :data="menuTree"
                         show-checkbox
                         ref="roleMenu"
                         node-key="id"
                         :check-strictly="false"
                         empty-text="加载中，请稍候"
                         :props="defaultProps" :default-expand-all="isExpand"
                         style="width: 90%; max-height: 160px; overflow-y: scroll; min-height: 30px;"
                    >
                    </el-tree>
                </el-form-item>
                <el-form-item label="角色标识" prop="code">
                    <el-input prefix-icon="el-icon-coordinate" v-model="form.code" style="width: 90%"
                              placeholder="请输入角色标识"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="remark">
                    <el-input prefix-icon="el-icon-s-comment" v-model="form.remark" style="width: 90%"
                              placeholder="请输入角色描述"></el-input>
                </el-form-item>
            </el-form>
            
            <template #footer>
          <span class="dialog-footer align-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
            </template>
        </el-dialog>
        
        <!-- 数据详情界面 -->
        <el-dialog top="25vh" title="用户详情"
                   :visible.sync="dialogFormDetail"
                   append-to-body
                   :close-on-click-modal=false
                   width="30%"
        >
            <el-form ref="form" :model="form" label-width="120px">
                <el-form-item label="用户名" prop="username">
                    <el-input prefix-icon="el-icon-user-solid" v-model="form.username" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickname">
                    <el-input prefix-icon="el-icon-user" v-model="form.nickname" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input prefix-icon="el-icon-message" v-model="form.email" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="电话">
                    <el-input prefix-icon="el-icon-phone" v-model="form.mobile" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-input prefix-icon="el-icon-timer" v-model="form.createTime" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="启用状态">
                    <el-input prefix-icon="el-icon-star-off" v-model="form.status" style="width: 90%"
                              :disabled="true"></el-input>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>

import {page, roleMenus, roleMenuById, roleSave, roleEdit} from "@/api/system/role";
import dayjs from "dayjs";

export default {
    name: "Role",
    data() {
        return {
            loading: false, // 列表等待转圈
            tableData: [],
            total: 10,
            pageNum: 1,
            pageSize: 10,
            headerBg: 'headerBg',
            dialogFormVisible: false, // 用户新增弹窗状态
            form: {}, // 用户新增数据集合
            roles: {
                name: [
                    {required: true, message: '请输入角色名称', trigger: 'blur'},
                ],
                code: [
                    {required: true, message: '请输入角色标识', trigger: 'blur'},
                ],
                remark: [
                    {required: true, message: '请输入用户简述', trigger: 'blur'},
                ],
            },
            params: {}, // 查询条件
            dialogFormDetail: false, // 用户详情弹窗状态
            percent: 0,
            showProgress: false,
            
            menuTree: [],
            defaultProps: {
                children: "children",
                label: "label" // 和后端数据相对应
            },
            isExpand: false, // 树展开  // 菜单列表
        }
    },
    created() {
        this.load()
        this.renderMenuTree()
    },
    methods: {
        handleSizeChange(pageSize) {
            console.log(pageSize)
            this.pageSize = pageSize;
            this.load()
        },
        handleCurrentChange(pageNum) {
            console.log(pageNum)
            this.pageNum = pageNum
            this.load()
        },
        load() {
            this.loading = true
            page(this.pageNum, this.pageSize, this.params).then(res => {
                this.loading = false
                this.tableData = res.data.records;
                this.total = res.data.total;
            }).catch(() => this.loading = false)
        },
        changSwitch(row) { // 开关
        
        },
        add() { // 新增用户按钮
            this.dialogFormVisible = true
            this.form = {}
        },
        submitForm() { // 表单提交
            this.$refs["roleMenu"].validate(valid => {
                if (valid) {
                    const data = {
                        id: this.form.id,
                        name: this.form.name,
                        code: this.form.code,
                        remark: this.form.remark,
                        deleted: 0,
                        menuIds: this.getMenuAllCheckedKeys(),
                    }
                    if (this.form.id !== undefined) {
                        roleEdit(data).then(response => {
                            this.$message.success("修改成功");
                            this.dialogFormVisible = false;
                            this.load()
                        });
                    } else {
                        roleSave(data).then(response => {
                            this.$message.success("新增成功");
                            this.dialogFormVisible = false;
                            this.load()
                        });
                    }
                }
            });
        },
        
        handleDelete(user) { // 删除
        
        },
        handleDetail(row) {
            this.form = JSON.parse(JSON.stringify(row))
            this.dialogFormDetail = true
        },
        
        handleAvatarSuccess(res) { // 文件上传
            this.form.avatar = res.data
            this.$message.success("上传成功")
            // this.update()
        },
        
        // 编辑
        handleEdit(role) {
            this.form = role
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs.roleMenu.setCheckedKeys([]); // 清空已经选中的
            })
            roleMenuById(role.id).then(res => {
                this.$nextTick(() => {
                    res.data.forEach((id) => {
                        setTimeout(()=>{
                            this.$nextTick(()=>{
                                //给每个id对应的check选中
                                this.$refs.roleMenu.setChecked(id,true, true)
                            })
                        },10)
                    })
                })
            })
        },
        
        // 获取菜单树
        renderMenuTree() {
            roleMenus().then(res => {
                this.menuTree = []
                this.menuTree.push(res.data)
            })
        },
    
        // 所有已选中菜单节点数据
        getMenuAllCheckedKeys() {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.roleMenu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.roleMenu.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },
        
        //转换菜单数据结构
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children,
            };
        },
        
        // -------------------------------------上传头像前的校验----------------------------------
        beforeAvatarUpload(file) {
            const isPNG = file.type === 'image/png'
            const isLt2M = file.size / 1024 / 1024 < 2
            if (!isPNG) {
                this.$message.error('上传头像图片只能是 PNG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isPNG && isLt2M
        },
        
        // 时间格式化
        formatDate(row, column) {
            // 获取单元格数据
            let data = row[column.property]
            if (data == null) {
                return ''
            }
            return dayjs(data).format("YYYY-MM-DD HH:mm:ss");
        },
    }
}
</script>

<style scoped>
.align-footer {
    text-align: center;
}
</style>
